<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <BasicTable @register="registerTable" :searchInfo="searchInfo">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate">{{ t('sys.configuration.add') }}</a-button>
      </template>
      <template #title>
        <span>{{ tableTitle }}</span>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <div style="display: flex; justify-content: center">
            <TableAction :actions="getActions(record)" />
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'currentNode'">
          <span
            @click="handleProgressClick(record)"
            style="cursor: pointer; color: blue !important"
          >
            {{ record.currentNode }}/{{ record.maxNode }}
          </span>
        </template>
      </template>
    </BasicTable>
    <AccountModal @register="registerModal" @success="handleSuccess" />
    <DetailView @register="registerDetailView" @success="DetailViewSuccess" />
    <phaseView @register="registerphaseView" />
    <OnephaseView @register="registerOnephaseView" />
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { message, Tooltip } from 'ant-design-vue';
  import { reactive, ref, computed, h, onMounted, onUnmounted, watch } from 'vue';
  import { Progress } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '@/components/Table';
  import {
    getTasklistAPI,
    stopTaskAPI,
    taskStatusNumApi,
    finishTaskAPI,
  } from '@/api/demo/InformationMatching';
  import { PageWrapper } from '@/components/Page';
  import { useModal } from '@/components/Modal';
  import AccountModal from './AccountModal.vue';
  import DetailView from './DetailView.vue';
  import phaseView from './phaseView.vue';
  import OnephaseView from './OnephaseView.vue';
  import { searchFormSchema } from './account.data';
  import { useGo } from '@/hooks/web/usePage';
  import { useWebSocketStore } from '@/store/modules/websocket';
  import { useI18n } from '@/hooks/web/useI18n';
  const webSocketStore = useWebSocketStore();

  defineOptions({ name: 'AccountManagement' });

  const { t } = useI18n();
  const go = useGo();
  const [registerModal, { openModal }] = useModal();
  const [registerDetailView, { openModal: openDetailView }] = useModal();
  const [registerphaseView, { openModal: openphaseView }] = useModal();
  const [registerOnephaseView, { openModal: openOnephaseView }] = useModal();
  const searchInfo = reactive<Recordable>({});
  const total = ref(0);
  const taskStatusData = ref<any[]>([]);

  const tableTitle = computed(() => {
    const statusInfo = taskStatusData.value
      .map((item) => `${item.label}: ${item.value}`)
      .join(', ');
    return `${t('sys.informaionMatchaing.title')} ${t('sys.configuration.common')} ${total.value} ${t('sys.configuration.strip')} (${statusInfo})`;
  });

  const columns = computed(() => [
    {
      title: 'id',
      dataIndex: 'id',
      width: 50,
    },
    {
      title: t('sys.informaionMatchaing.columns.createUsername'),
      dataIndex: 'createUsername',
      width: 100,
    },
    {
      title: t('sys.informaionMatchaing.columns.createTime'),
      dataIndex: 'createTime',
      width: 120,
    },
    {
      title: t('sys.informaionMatchaing.columns.title'),
      dataIndex: 'title',
      width: 120,
    },
    // {
    //   title: t('sys.configuration.describe'),
    //   dataIndex: 'remark',
    //   width: 120,
    //   customRender: ({ text }: { text: string }) => {
    //     return h(
    //       Tooltip,
    //       {
    //         title: text,
    //       },
    //       [
    //         h(
    //           'span',
    //           {
    //             style: {
    //               display: 'inline-block',
    //               width: '100%',
    //               height: 'auto',
    //               overflow: 'hidden',
    //               textOverflow: 'ellipsis',
    //               whiteSpace: 'nowrap',
    //             },
    //           },
    //           text,
    //         ),
    //       ],
    //     );
    //   },
    // },
    {
      title: t('sys.informaionMatchaing.columns.category'),
      dataIndex: 'category',
      width: 120,
    },
    {
      title: t('sys.informaionMatchaing.columns.status'),
      dataIndex: 'status',
      width: 120,
      customRender: ({ record }: { record: Recordable }) => {
        if (record.status === t('sys.configuration.inProgress')) {
          if (record.status1 !== t('sys.configuration.taskSucces')) {
            return `一阶段状态 ${record.status1}`;
          } else {
            return `二阶段状态 ${record.status2}`;
          }
        }
        return record.status;
      },
    },
    {
      title: t('sys.informaionMatchaing.columns.type'),
      dataIndex: 'type',
      width: 80,
      customRender: ({ record }: { record: Recordable }) => {
        return record.type == 'orientation' ? t('sys.informaionMatchaing.columns.orientation') : t('sys.informaionMatchaing.columns.match');
      },
    },
    {
      title: t('sys.informaionMatchaing.columns.currentNode'),
      dataIndex: 'currentNode',
      width: 180,
    },
    {
      title: t('sys.informaionMatchaing.columns.success'),
      dataIndex: 'success',
      width: 100,
      customRender: ({ record }: { record: Recordable }) => {
        const success = record.success ?? '-';
        const maxNum = record.maxNum ?? '-';
        return `${success}/${maxNum}`;
      },
    },
    {
      title: t('sys.informaionMatchaing.columns.repeatRate'),
      dataIndex: 'repeatRate',
      width: 180,
      customRender: ({ record }: { record: Recordable }) => {
        const repeatRate =
          record.repeatRate !== 0 ? (record.repeatRate * 100).toFixed(2) + '%' : '0';
        const validRate = record.validRate !== 0 ? (record.validRate * 100).toFixed(2) + '%' : '0';
        const spendTime = formatSpendTime(record.spendTime); // 使用 formatSpendTime 函数
        return `${repeatRate}/${validRate}/${spendTime}`;
      },
    },
    {
      title: t('sys.configuration.action'),
      dataIndex: 'action',
      width: 250,
      key: 'action',
      fixed: 'right', // 添加这一行来固定列到右侧
    },
  ]);

  const [registerTable, { reload, updateTableDataRecord, getDataSource }] = useTable({
    title: tableTitle,
    api: async (params) => {
      const result = (await getTasklistAPI(params)) as { items: any[]; total: number };
      total.value = result.total;
      return result;
    },
    rowKey: 'id',
    columns: columns.value,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
    },
    showIndexColumn: false,
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    handleSearchInfoFn(info) {
      return info;
    },
  });

  function getActions(record: Recordable) {
    const actions = [
      {
        label: '一阶段',
        tooltip: '一阶段详情',
        onClick: handlePhaseView.bind(null, record),
      },
      {
        label: '二阶段',
        tooltip: '二阶段详情',
        onClick: handleView.bind(null, record),
      },
      {
        label: '完成采集',
        tooltip: '完成采集',
        disabled: record.status != '采集中',
        onClick: gather.bind(null, record),
      },
    ];

    actions.push({
      label: '停止',
      color: 'error',
      tooltip: '停止任务',
      disabled: record.status == t('sys.configuration.taskSucces') || record.status == t('sys.configuration.taskStop'),
      popConfirm: {
        title: '是否停止此任务',
        placement: 'left',
        confirm: handleStop.bind(null, record),
      },
    });

    return actions;
  }

  //停止任务
  async function handleStop(record: Recordable) {
    let Data = await stopTaskAPI({ id: record.id });
    if (Data.code == 200) {
      message.success('操作完成');
    }
  }
  function formatSpendTime(spendTime: number): string {
    if (!spendTime) return '0';

    const totalSeconds = Math.floor(spendTime / 1000);
    const minutes = Math.floor(totalSeconds / 60);
    const seconds = totalSeconds % 60;

    return `${minutes}分${seconds}秒`;
  }
  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  function handleSuccess({ isUpdate, values }) {
    if (isUpdate) {
      const result = updateTableDataRecord(values.id, values);
    } else {
      reload();
    }
  }

  async function gather(record: Recordable) {
    let data = await finishTaskAPI(record.id);
    if (data.code == 200) {
      message.success('中止完成');
      reload();
    }
  }

  function handleView(record: Recordable) {
    openDetailView(true, {
      record,
    });
  }

  function handlePhaseView(record: Recordable) {
    openOnephaseView(true, {
      record,
    });
  }

  function DetailViewSuccess(record: Recordable) {
    // 处理 DetailView 成功后的逻辑
    // openphaseView(true, {
    //   record,
    // });
  }

  function handleProgressClick(record: Recordable) {
    openphaseView(true, {
      record,
    });
  }

  async function taskStatusNum() {
    let Data = await taskStatusNumApi();
    taskStatusData.value = Data.data;
  }

  let intervalId: ReturnType<typeof setInterval>;

  onMounted(() => {
    taskStatusNum(); // 获取数据统计
    // intervalId = setInterval(() => {
    //   reload();
    // }, 5000);
  });

  onUnmounted(() => {
    clearInterval(intervalId);
  });

  watch(
    () => webSocketStore.$state,
    (newState, oldState) => {
      console.log('webSocketStore state changed:', newState, oldState);
      // 在这里可以执行一些操作，例如更新表格数据
      const recordList = newState.recordList;
      if (recordList && recordList.length > 0) {
        recordList.forEach((record) => {
          if (record.type == '信息匹配') {
            const tableRecord = findTableRecordById(record.code);
            if (tableRecord) {
              updateTableDataRecord(tableRecord.id, { [record.key]: record.value });
            }
          }
        });
      }
    },
    { deep: true },
  );

  function findTableRecordById(id: string): Recordable | undefined {
    const tableData = getDataSource();
    const tableRecord = tableData.find((record) => record.id == id);
    if (tableRecord) {
      updateTableDataRecord(tableRecord.id, { status: tableRecord.status });
    }
    return tableRecord;
  }
</script>
